<template>
  <div class="shipment-order-status-wrapper app-container" v-loading="loading">
    <div class="shipment-order-content">
      <el-form label-width="108px" :model="form" ref="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item :label="$t('outBound.status')" prop="shipmentOrderNo">
              <el-tag> {{ shipmentStatusMap.get(form.shipmentOrderStatus + '') }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('outBound.type')" prop="shipmentOrderType">{{ $t('outBound.E-commerce outbound') }}
              <!-- {{ selectDictLabel(dict.type.wms_shipment_type, form.shipmentOrderType) }} -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item :label="$t('outBound.OrderNo')" prop="shipmentOrderNo">{{ form.shipmentOrderNo }}</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('order.orderNo')" prop="orderNo">{{ form.orderNo }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item :label="$t('common.customer')" prop="customerId">{{ customerMap.get(form.customerId) }}</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('common.remark')" prop="remark">{{ form.remark }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider />

      <!-- 如果有出库指令 -->
      <div v-if="InstructionsList && ifBoxCode">
        <div class="table" style="margin: 20px 0">
          <InstructionTable :data-list="InstructionsList" :shipment-order-id="form.orderId"  :receipt-show="true"  @getList="getList" />
        </div>
      </div>

      <!-- 物流信息 -->
      <div class="flex-center mb8">
        <div class="flex-one large-tip bolder-font">{{ $t('outBound.Logistics') }}</div>
        <div class="ops">
          <el-button v-if="mergeDetailStatusArray.length === 1" type="primary" plain="plain" size="small"
            @click="deliveryAdd">{{ $t('outBound.addcourier') }}
          </el-button>
        </div>
      </div>

      <!-- 物流信息表格 -->
      <div class="table">
        <WmsTable v-loading="loading" :data="form.delivery" @selection-change="handleSelectionChange">
          <el-table-column :label="$t('outBound.DeliveryId')" align="center" prop="shipmentOrderId" v-if="columns[0].visible" />
          <el-table-column :label="$t('oiutBound.carrier')" align="center" :formatter="getCarrier" prop="carrierId"
            v-if="columns[1].visible" />
          <el-table-column :label="$t('outBound.issuateDate')" align="center" prop="deliveryDate" width="180" v-if="columns[2].visible">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.deliveryDate, '') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('outBound.trackingNo')" align="center" prop="trackingNo" v-if="columns[3].visible">
            <!--        https://www.kuaidi100.com/chaxun?com=[]&nu=[]-->
            <template slot-scope="scope">
              <a target="_blank"
                :href="'https://www.kuaidi100.com/chaxun?com=' + getCarrier(scope.row) + '&nu=' + scope.row.trackingNo">{{
                  scope.row.trackingNo
                }}
              </a>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.remark')" align="center" prop="remark" v-if="columns[4].visible" />
        </WmsTable>
      </div>

      <!-- 物料明细 -->
      <div v-if="!ifBoxCode">
        <el-row class="mb8 mt10" :gutter="10">
          <el-col :span="1.5">
            <div class="flex-one large-tip bolder-font">{{ $t('common.MaterialDetails') }}</div>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" type="success" plain="plain" icon="el-icon-delete-location"
              @click="onBatchSetInventory">
              {{ $t('common.batchSetWarehouse') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain="plain" size="small"
              @click="batch(1)">{{ $t('common.batchSetOutboundStatus') }}
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button size="small" icon="el-icon-check" type="warning" plain="plain" @click="dialogFormVisible = true">
              {{ $t('outBound.Allocate warehouse/storage area') }}
            </el-button>
          </el-col>

        </el-row>
        <div class="table">
          <el-form ref="form" :model="form" :show-message="false">
            <WmsTable :data="form.details" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"
                :selectable="(row) => !row.finish"></el-table-column>
              <el-table-column :label="$t('common.MaterialName')" align="center" prop="prod.itemName"></el-table-column>
              <el-table-column :label="$t('common.MaterialNo')" align="center" prop="prod.itemNo"></el-table-column>
              <el-table-column :label="$t('common.MaterialType')" align="center" prop="prod.itemType"></el-table-column>
              <el-table-column :label="$t('common.planNumber')" align="center" prop="planQuantity"></el-table-column>
              <el-table-column :label="$t('common.Actual Quantity')" align="center" width="150">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.realQuantity" :min="1" :max="2147483647" size="small"
                    :disabled="scope.row.finish"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.Warehouse/storage area')" align="center" width="200">
                <template slot-scope="scope">
                  <el-form-item :prop="'details.' + scope.$index + '.place'"
                    :rules="[{ required: true, message: $t('common.pleaseInput'), trigger: 'change' }]"
                    style="margin-bottom: 0!important;">
                    <!-- <WmsWarehouseCascader v-model="scope.row.place" size="small" :disabled="scope.row.finish">
                    </WmsWarehouseCascader> -->
                    <WmsAreaCascader v-model="scope.row.place" size="small" :disabled="scope.row.finish"></WmsAreaCascader>

                    
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('outBound.status')" width="150">
                <template slot-scope="{ row }">
                  <DictSelect v-model="row.shipmentOrderStatus" :options="row.range" size="small" :disabled="row.finish">
                  </DictSelect>
                </template>
              </el-table-column>
            </WmsTable>
          </el-form>
          <el-empty v-if="!form.details || form.details.length === 0" :image-size="48"></el-empty>
        </div>
        <div class="tc mt16">
          <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
          <el-button @click="submitForm" type="primary" :disabled="finish">{{ $t('common.save') }}</el-button>
        </div>
      </div>

      <!-- 箱子明细 -->
      <div v-else>
        <BoxChoose :form="form" :from-type="'OUT'" @refresh="loadDetail($route.query.id)" />
      </div>
      <!-- 添加或修改发货记录对话框 -->
      <el-dialog :title="deliveryTitle" :visible.sync="deliveryOpen" width="50%" append-to-body>
        <el-form ref="deliveryForm" :model="deliveryForm" :rules="rules" label-width="108px" inline
          class="dialog-form-two">
          <el-form-item :label="$t('order.OutboundOrder')" prop="shipmentOrderId">
            <el-input v-model="deliveryForm.shipmentOrderId" disabled :placeholder="$t('common.pleaseInput')" />
          </el-form-item>
          <el-form-item :label="$t('oiutBound.carrier')" prop="carrierId">
            <wms-carrier-select v-model="deliveryForm.carrierId"></wms-carrier-select>
          </el-form-item>
          <el-form-item :label="$t('outBound.issuateDate')" prop="deliveryDate">
            <el-date-picker clearable size="small" v-model="deliveryForm.deliveryDate" type="datetime"
              value-format="yyyy-MM-ddTHH:mm:ss" :placeholder="$t('common.placeholderSelect')">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('outBound.trackingNo')" prop="trackingNo">
            <el-input v-model="deliveryForm.trackingNo" :placeholder="$t('common.pleaseInput')" />
          </el-form-item>
          <el-form-item :label="$t('common.remark')" prop="remark">
            <el-input v-model="deliveryForm.remark" :placeholder="$t('common.pleaseInput')" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitdeliveryForm">{{ $t('common.confirm') }}</el-button>
          <el-button @click="canceldeliveryForm">{{ $t('common.cancel') }}</el-button>
        </div>
      </el-dialog>
      <BatchWarehouseDialog :visible.sync="batchDialogVisible" :form-data.sync="batchForm"
        @confirmed="onBatchDialogFinished"></BatchWarehouseDialog>
      <el-dialog :title="$t('outBound.looooogMsg')" :visible.sync="dialogFormVisible" width="400px">
        <el-form :model="dialogForm">
          <el-form-item :label="$t('outBound.allocationpolicy')" label-width="98px">
            <el-select v-model="dialogForm.region" :placeholder="$t('common.placeholderSelect')">
              <el-option :label="$t('outBound.allocationpolicyList.1')" :value="1"></el-option>
              <el-option :label="$t('outBound.allocationpolicyList.2')" :value="2"></el-option>
              <el-option :label="$t('outBound.allocationpolicyList.3')" :value="3" disabled></el-option>
              <el-option :label="$t('outBound.allocationpolicyList.4')" :value="4" disabled></el-option>
              <el-option :label="$t('outBound.allocationpolicyList.5')" :value="5" disabled></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="allocated()">{{ $t('common.confirm') }}</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="$t('common.placeholderSelect')" :visible.sync="open" width="50%" append-to-body="append-to-body">
          <DictRadio v-model="dialogStatus" :radioData="dialogStatusRange"></DictRadio>
          <div class="dialog-footer" slot="footer">
            <el-button type="primary" @click="dialogConfirm">{{ $t('common.confirm') }}</el-button>
            <el-button @click="cancelDialog">{{ $t('common.cancel') }}</el-button>
          </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getInstruct } from '@/api/order/index.js'
import { addOrUpdateWmsShipmentOrder, allocatedInventory, getWmsShipmentOrder } from '@/api/wms/shipmentOrder'
import ItemSelect from '@/views/components/ItemSelect'
import { mapGetters } from 'vuex'
import WmsCarrier from "@/views/wms/carrier/index.vue";
import { addWmsDelivery, updateWmsDelivery } from "@/api/wms/delivery";
import BatchWarehouseDialog from "@/views/components/wms/BatchWarehouseDialog/index.vue";
import { ShipmentOrderConstant } from "@/constant/ShipmentOrderConstant.ts";
import BoxListComponent from "@/views/components/wms/BoxList/index.vue";
import WmsAreaCascader from "@/components/WmsAreaCascader";
import request from '@/utils/request.js'

import InstructionTable from '@/views/wms/shipmentOrder/instructionTable/index.vue'
import BoxChoose from '@/views/wms/receiptOrder/component/boxChoose.vue'
export default {
  name: 'WmsShipmentOrder',
  props: {
    checkbox: {
      type: Boolean,
      default: true,
    }
  },
  components: { BatchWarehouseDialog, WmsCarrier, ItemSelect, BoxListComponent, WmsAreaCascader, InstructionTable, BoxChoose },
  dicts: ['wms_shipment_type', 'wms_shipment_status'],
  computed: {
    ShipmentOrderConstant() {
      return ShipmentOrderConstant
    },
    ...mapGetters(['customerMap', 'carrierMap']),
    shipmentStatusMap() {
      let obj = this.dict.type.wms_shipment_status.map(item => [item.value, item.label])
      let map = new Map(obj)
      return map
    },
    mergeDetailStatusArray() {
      const arr = this.sourceDetails || []
      return [...new Set(arr.filter(it => it.shipmentOrderStatus !== null).map(it => it.shipmentOrderStatus))]
    },
    dialogStatusRange() {
      if (this.mergeDetailStatusArray.length !== 1) {
        return []
      }
      return this.getRange(this.mergeDetailStatusArray[0])
    },
    ifBoxCode() {
      if (this.form.outType === 'BOX') {
        return true
      } else {
        return false
      }
    },
  },
  data() {
    return {
      // 分配仓库
      dialogFormVisible: false,
      dialogForm: {
        date1: '',
      },
      // 批量设置仓库/库区
      batchDialogVisible: false,
      batchForm: {
        place: []
      },
      open: false,
      // 遮罩层
      loading: true,
      ids: [],
      // 表单参数
      form: {
        details: []
      },
      sourceDetails: [],
      // 表单校验
      rules: {},
      dialogStatus: null,
      // 非多个禁用
      multiple: true,
      finish: false,
      // 物流管理
      deliveryTitle: '',
      shipmentOrderId: null,
      deliveryOpen: false,
      deliveryForm: {},
      columns: [
        { key: 1, label: "出库单主表Id", visible: false },
        { key: 2, label: "承运商Id", visible: true },
        { key: 3, label: "发货日期", visible: true },
        { key: 4, label: "快递单号", visible: true },
        { key: 5, label: this.$t('common.remark'), visible: true },
      ],
      boxCode: null,
      // 扫码枪扫过的右侧箱子列表
      leftFixedBoxes: [],
      // 模拟数据，可删除
      InstructionsList: [],
    }
  },
  created() {
    const { id } = this.$route.query
    if (id) {
      this.shipmentOrderId = id
      this.loadDetail(id)
    } else {
      this.cancel()
    }
  },
  methods: {
    /** 自动分配 仓库/库区 */
    allocated() {
      allocatedInventory({ id: this.shipmentOrderId, type: this.dialogForm.region }).then(response => {
        this.$modal.msgSuccess(this.$t('common.succcessInfo'));
        this.dialogFormVisible = false;
        this.loadDetail(this.shipmentOrderId)
      });
    },
    /** 批量设置仓库/库区 */
    onBatchSetInventory() {
      const { details } = this.form
      if (!details || details.length === 0) {
        this.$modal.msgError(this.$t('common.pleaseAddSKU'))
        return
      }
      // 未选中
      if (!this.ids.length) {
        this.$modal.msgError(this.$t('common.pleaseSelectSKU'))
        return
      }
      this.batchDialogVisible = true
    },
    /** 批量设置仓库/库区 完成事件 */
    onBatchDialogFinished() {
      this.batchDialogVisible = false
      const [warehouseId, areaId, rackId] = this.batchForm.place || []
      this.form.details.forEach(it => {
        // 仅更新已选中
        if (this.ids.includes(it.id)) {
          it.place = [warehouseId, areaId, rackId].filter(Boolean)
        }
      })
    },
    // 格式化承运商
    getCarrier(row, column) {
      return this.carrierMap.get(row.carrierId)
    },
    // 新增物流对话框，提交按钮
    submitdeliveryForm() {
      this.$refs["deliveryForm"].validate(valid => {
        if (valid) {
          if (this.deliveryForm.id != null) {
            updateWmsDelivery(this.deliveryForm).then(response => {
              this.$modal.msgSuccess(this.$t('common.succcessInfo'));
              this.deliveryOpen = false;
              this.loadDetail(this.shipmentOrderId)
            });
          } else {
            addWmsDelivery(this.deliveryForm).then(response => {
              this.$modal.msgSuccess(this.$t('common.succcessInfo'));
              this.deliveryOpen = false;
              this.loadDetail(this.shipmentOrderId)
            });
          }
        }
      });
    },
    // 新增物流对话框，取消按钮
    canceldeliveryForm() {
      this.deliveryOpen = false
    },
    // 新增物流信息
    deliveryAdd() {
      this.deliveryTitle = this.$t('common.newadd')
      this.deliveryOpen = true
      this.deliveryForm.shipmentOrderId = this.shipmentOrderId
    },
    dialogConfirm() {
      if (!this.dialogStatus) {
        this.$modal.alert(this.$t('common.pleaseSelectoutboundstatus'))
        return
      }
      // ifBoxCode判断是物料还是箱子出库
      this.form.details.forEach(detail => {
        if (this.ids.includes(detail.id) || this.ifBoxCode) {
          // console.log('enter', 11)
          detail.shipmentOrderStatus = this.dialogStatus
        }
      })
      // console.log('this.form.details', this.form.details)
      this.cancelDialog()
    },
    cancelDialog() {
      this.open = false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    batch(num) {
      if (num === 1 && this.multiple) {
        this.$modal.alert(this.$t('common.pleaseSelectSKU'))
      } else {
        this.open = true
        this.dialogStatus = null
      }
    },
    cancel() {
      this.$tab.closeOpenPage({ path: '/wms/shipmentOrder' })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.$notify({
            title: this.$t('common.warning'),
            message: this.$t('common.pleaseImproveInf'),
            type: 'warning'
          });
          return
        }
        const details = !this.ifBoxCode ? this.form.details.map(it => {
          console.log('it', it)
          if (it.place) {
            it.prod.warehouseId = it.place[0] ? it.place[0] : ''
            it.prod.areaId = it.place[1] ? it.place[1] : ''
            it.prod.rackId = it.place[2] ? it.place[2] : ''
          } else {
            it.prod.warehouseId = null
            it.prod.areaId = null
            it.prod.rackId = null
          }
          return {
            id: it.id,
            itemId: it.prod.id,
            rackId: it.prod.rackId,
            areaId: it.prod.areaId,
            warehouseId: it.prod.warehouseId,
            planQuantity: it.planQuantity,
            realQuantity: it.realQuantity,
            shipmentOrderStatus: it.shipmentOrderStatus,
            delFlag: 0
          }
        }) : 
        this.form.details
        // this.$refs.boxList.listData
        // 加上出库指令InstructionsList
        const req = { ...this.form, details }
        if (req.details.some(element => element.shipmentOrderStatus === null)) {
          this.$message.error(this.$t('common.pleaseselectboxoutboundstatus'))
          return
        }
        if(details.length === 0) {
          this.$message.error(this.$t('common.pleaseaddbox'))
        }
        delete req.createTime
        req.details.map(r=>{
          delete r.createTime
        })        
        // console.log('req', req)
        // return
        addOrUpdateWmsShipmentOrder(req).then(response => {
          if (response.code == 398) {
            return
          }
          this.$modal.msgSuccess(this.$t('common.succcessInfo'))
          this.cancel()
        })
      })
    },
    loadDetail(id) {
      this.loading = true
      getWmsShipmentOrder(id).then(response => {
        const { details, items } = response
        const map = {};
        (items || []).forEach(it => {
          map[it.id] = it
        })
        details && details.forEach(it => {
          it.prod = map[it.itemId]
          if ((!it.place || it.place.length === 0) && it.prod) {
            it.place = it.prod.place;
          }
          it.range = this.getRange(it.shipmentOrderStatus)
          it.finish = it.shipmentOrderStatus === 13
        })
        this.sourceDetails = details.map(it => ({ ...it }))
        this.finish = details.filter(it => !it.finish)?.length === 0
        this.form = {
          ...response,
          details
        }
        this.getList()
      }).finally(() => {
        this.loading = false
      })
    },
    getList() {
      getInstruct({orderId: this.form.orderId}).then((res) => {
        res.content.map(r=>{
          if(r.status === 'INIT') {
            r.status = this.$t('inst.status.unfinish')
          } else if(r.status === 'FINISH') {
            r.status = this.$t('inst.status.finished')
          }
          // 表格默认编辑状态false
          r.editRows = false
        })
        this.InstructionsList = res.content
      })
    },
    getRange(status) {
      const arr = this.dict.type.wms_shipment_status
      if (status === 4 || status === 3) {
        return arr.filter(it => +it.value === status).map(it => ({ label: it.label, value: it.value }))
      }
      if (status === 2) {
        return arr.filter(it => +it.value >= status && +it.value !== 4).map(it => ({
          label: it.label,
          value: it.value
        }))
      }
      return arr.filter(it => +it.value >= status).map(it => ({ label: it.label, value: it.value }))
    },
    returnBoxData(data) {
      if (data.content) {
        return data.content;
      }
    },
  }
}
</script>
<style lang="stylus">
.shipment-order-status-wrapper
  .shipment-order-content
    width 70%
    min-width 900px
    margin 0 auto
.table-box
  display flex
  justify-content space-between
.table-box-left
  width 100%
.table-box-right
  width 100%
</style>
